#encoding:utf-8
from flask import Flask,render_template,request,redirect,url_for,session,g,jsonify

import config
from models import User,Record,Answer,ConsumeType
from models import UserScheme,RecordScheme,ConsumeTypeScheme
from exts import db
from decorators import login_requisite
from sqlalchemy import or_
from marshmallow import pprint

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)

@app.route('/')
@login_requisite
def index():
    # content={
    #     'records':Record.query.order_by('-create_time').all()
    # }
    # return render_template('index.html',**content)
    # return render_template('login.html')

    user = g.user
    content={
     'records':user.records
    }
    return render_template('index.html',**content)

@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')
    else:
        telephone = request.form.get('telephone')
        password = request.form.get('password')

        user = User.query.filter(User.telephone==telephone).first()
        if user and user.check_password(password):
            session['user_id']=user.id
            #cookie 31天有效
            session.permanent=True
            return redirect(url_for('index'))
        else:
            return u'手机号或者密码错误，请重新输入！'

@app.route('/regist/',methods=['GET','POST'])
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        username = request.form.get('username')
        telephone = request.form.get('telephone')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        user = User.query.filter(User.telephone == telephone).first()
        if user:
            return u'该手机号码已经被注册，请换一个手机号注册！'
        else:
            if password1 != password2:
                return u'输入的两个密码不一致，请重新输入！'
            else:
                print 'user.username:%s'% username
                user2 = User(telephone=telephone,username=username,password=password2)
                db.session.add(user2)
                db.session.commit()

                return redirect(url_for('login'))

@app.route('/logout/')
def logout():
    session.pop('user_id')
    # del session['user_id']
    # session.clear()
    return redirect(url_for('login'))

@app.route('/record/',methods=['GET','POST'])
@login_requisite
def record():
    if request.method == 'GET':
        ctypeList = db.session.query(ConsumeType).all()
        return render_template('question.html',ctypeList=ctypeList)
    else:

        title = request.form.get('title')
        content = request.form.get('content')
        ctype = request.form.get('ctype')

        print 'ctype:%s'%ctype
        print type(ctype)

        consumeType = ConsumeType.query.filter(ConsumeType.id==int(ctype)).first()

        record0 = Record(title = title,content=content)
        record0.author=g.user
        record0.consumeType=consumeType
        db.session.add(record0)
        db.session.commit()
        return redirect(url_for('index'))

@app.route('/consumeType/',methods=['GET','POST'])
@login_requisite
def consumeType():
    if request.method == 'GET':
        return render_template('consumeType.html')
    else:
        consumeType0 = request.form.get('consumeType')

        consumeTypeModel = ConsumeType(title = consumeType0)
        db.session.add(consumeTypeModel)
        db.session.commit()
        return redirect(url_for('index'))


#问答详情页
@app.route('/detail/<record_id>')
def detail(record_id):

    record_model = Record.query.filter(Record.id==record_id).first()

    return render_template('detail.html',record=record_model)

#评论
@app.route('/add_answer/',methods=['GET','POST'])
@login_requisite
def add_answer():
    answer_content = request.form.get('answer-content')
    answer0 = Answer(content=answer_content)
    answer0.author=g.user
    record_id = request.form.get('record_id')
    record0 = Record.query.filter(Record.id==record_id).first()
    answer0.record=record0
    db.session.add(answer0)
    db.session.commit()

    return redirect(url_for('detail',record_id=record_id))

#搜索
@app.route('/search/')
def search():
    p = request.args.get('p')
    #'或'查询
    contents = Record.query.filter(or_(Record.title.contains(p),Record.content.contains(p))).order_by('-create_time')
    #'与'查询
    #contents = Record.query.filter((Record.title.contains(p),Record.content.contains(p))).order_by('-create_time')

    return render_template('index.html',records=contents)

#删除
@app.route('/delete/<record_id>')
def delete(record_id):
    record = Record.query.filter(Record.id == record_id).first()
    db.session.delete(record)
    db.session.commit()
    return redirect(url_for('index'))

#编辑
@app.route('/edit/<record_id>',methods=['GET','POST'])
def edit(record_id):
    if request.method=='GET':
        record = Record.query.filter(Record.id==record_id).first()
        return render_template('edit.html',record=record)
    else:
        title = request.form.get('record-header')
        content = request.form.get('record-content')
        record = Record.query.filter(Record.id == record_id).first()
        record.title = title
        record.content = content
        db.session.commit()
        return redirect(url_for('detail',record_id=record_id))



#记录列表接口
@app.route('/get/recordList',methods=['GET','POST'])
def recordList():
    if request.method == 'POST':
        requestJsonString = request.form.to_dict()
        requestDict = eval(requestJsonString.keys()[0])
        username = requestDict.get('username')
        password = requestDict.get('password')

        telephone = username
        password = password

        user = User.query.filter(User.telephone == telephone).first()
        if user and user.check_password(password):
            userScheme = UserScheme()
            # 序列化成json
            result = userScheme.dump(user)
            # 序列化成json字符串
            # result = userScheme.dumps(user)
            # pprint(result.data)

            # 反序列化到data
            # user_data = {
            #     'username': 'Ronnie',
            #     'records': 'ronnie@stones.com'
            # }
            # userModel = userScheme.load(user_data)
            # pprint(userModel.username)

            return jsonify({'user': result.data})
        else:
            return jsonify({'user': "空"})

    elif request.method == 'GET':
        return jsonify({'user': "空"})

#消费类型接口
@app.route('/get/consumeTypeList',methods=['GET'])
def getConsumeTypeList():
    consumeTypeList = db.session.query(ConsumeType).all()
    if consumeTypeList:
        dict_list = []
        ctScheme = ConsumeTypeScheme()
        for consumeType in consumeTypeList:
            result = ctScheme.dump(consumeType)
            obj = result.data
            dict_list.append(obj)

    return jsonify({'consumeTypeList': dict_list})

#批量导入原始数据
def batchInsertInitData():

    title_list = [u'餐饮', u'购物', u'日用', u'交通', u'蔬菜', u'水果', u'零食', u'运动', u'娱乐', u'通讯', u'服饰', u'美容', u'住房', u'居家', u'孩子', u'长辈',
              u'社交', u'旅行', u'烟酒', u'数码', u'汽车', u'医疗', u'书籍', u'学习', u'宠物', u'礼金', u'礼物', u'办公', u'维修', u'捐赠', u'彩票', u'设置']
    object_list = []
    dict_list = []

    for title2 in title_list:
        titleModel = ConsumeType(title=title2)
        object_list.append(titleModel)

    for item in object_list:
        item_dict = item.__dict__
        if "_sa_instance_state" in item_dict:
            del item_dict["_sa_instance_state"]
            dict_list.append(item_dict)

    db.session.execute(ConsumeType.__table__.insert(dict_list))
    db.session.commit()


#钩子函数,上下文处理器，执行的时机在return前
@app.context_processor
def my_context_processor():
    if hasattr(g,'user'):
        return {'user':g.user}
    #如果没有值，要传空字典过去
    return {}

# before_request -> 视图函数 -> 上下文处理器 -> return
#钩子函数，执行的时机在请求接收前
@app.before_request
def my_before_request():
    user_id = session.get('user_id')
    if user_id:
        user = User.query.filter(User.id==user_id).first()
        if user:
            g.user = user

if __name__ == '__main__':
    app.run()
